<?php
/**
 * Timfan design模块处理程序
 *
 * @author Tim Fan
 * QQ:1026073477
 * @url http://i-fanr.com/
 */
defined('IN_IA') or exit('Access Denied');
define("MICRO_TEST", "micro_test");
require_once IA_ROOT . "/addons/" . MICRO_TEST . "/jssdk.class.php";
require_once IA_ROOT . "/addons/" . MICRO_TEST . "/timUtil.class.php";
class Micro_testModuleSite extends WeModuleSite {
	public $weid;
	public $acid;
	function __construct()
	{
		global $_W;
		$this->weid = $_W['uniacid'];
		
	}

	public function doMobileIndex() {
		global $_W,$_GPC;
		$openid = $_W['openid'];
		$acid = $_W['acid'];
		load()->classs('weixin.account');
		$accObj= WeixinAccount::create($acid);
		$access_token = $accObj->fetch_token();
		$userInfo = $this->getUserInfo ($access_token, $openid);
		$nickname = $userInfo['nickname'];
		$member = pdo_fetch("SELECT * FROM ".tablename('micro_test_user')." WHERE nickname = :nickname", array(':nickname' => $nickname));
		$score = intval($_GPC['score']);
		if(!empty($member)) { 
			$data = array(
				"openid" => $userInfo['openid'],
				"nickname" => $userInfo['nickname'],
				"headimgurl" => $userInfo['headimgurl'],
				"score" => $score,
			);
			pdo_update('micro_test_user', $data, array('nickname' => $nickname));
		}
		
		include $this->template('index');
	}

	public function doMobileLogin() {
		include $this->template('login');
	}
	
	public function doMobileCover1() { 
		global $_W,$_GPC;
		$openid = $_W['openid'];
		$acid = $_W['acid'];
		load()->classs('weixin.account');
		$accObj= WeixinAccount::create($acid);
		$access_token = $accObj->fetch_token();
		$userInfo = $this->getUserInfo ($access_token, $openid);
		$nickname = $userInfo['nickname'];
		$phone = $_GPC['phone'];
		$company = $_GPC['company'];
		if(empty($phone) ||empty($company)) { 
			echo "<script>alert('请填写完整')</script>";
			include $this->template('login');
		}else{
		$member = pdo_fetch("SELECT * FROM ".tablename('micro_test_user')." WHERE nickname = :nickname", array(':nickname' => $nickname));
		if(empty($member) && $openid!==NULL) { 
			$data = array(
				"openid" => $userInfo['openid'],
				"nickname" => $userInfo['nickname'],
				"headimgurl" => $userInfo['headimgurl'],
				"phone" => $phone,
				"company" => $company,
				"score" => 0,
			);
			pdo_insert('micro_test_user', $data);//添加数据
		}else{ 
			$datas = array(
				"openid" => $userInfo['openid'],
				"nickname" => $userInfo['nickname'],
				"phone" => $phone,
				"company" => $company,
		);
			pdo_update('micro_test_user', $datas, array('nickname' => $nickname));
		}
		$list = pdo_fetchall("SELECT * FROM ".tablename('micro_test')." ORDER BY id ASC");
		$sets = pdo_fetchall("SELECT * FROM ".tablename('micro_testsetting'));
		foreach ($list as $key => $value) {
			$dat[] = array(
				'question' =>$value['question'],
				'answers' =>array($value['ans_a'],$value['ans_b'],$value['ans_c'],$value['ans_d']),
				'correctAnswer' =>$this->_zh($value['correct_ans']),
			);
		}
		include $this->template('index');
		}
	}

	private function _zh($cans) { 
		switch ($cans)
		{
			case A:
			  return "1";
			  break;
			case B:
			  return "2";
			  break;
			case C:
			  return "3";
			  break;
			case D:
		      return "4";
			break;
			default:
			  return "Undefined";
		};
	}
	public function doWebTest() {
		global $_W,$_GPC;
		$weid = $_W['weid'];
		$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
		load()->func('tpl');
		if('post' == $op){//添加或修改
			$id = intval($_GPC['id']);
			if(!empty($id)){
			$item = pdo_fetch("SELECT * FROM ".tablename('micro_test')." where id=$id");
			empty($item)?message('亲,数据不存在！', '', 'error'):"";	
			}
			$info = pdo_fetch("SELECT * FROM ".tablename('micro_testsetting'));
 			
			if(checksubmit('submit')){
				empty ($_GPC['question'])?message('亲,问题不能为空'):$question=$_GPC['question'];
			$ans_a =$_GPC['ans_a'];
			$ans_b =$_GPC['ans_b'];
			$ans_c =$_GPC['ans_c'];
			$ans_d =$_GPC['ans_d'];
			$correct_ans =$_GPC['correct_ans'];
				$data = array(
					'id'=>$id,
					'question' =>$question,
					'ans_a'=>$ans_a,
					'ans_b'=>$ans_b,
					'ans_c'=>$ans_c,
					'ans_d'=>$ans_d,
					'correct_ans'=>$correct_ans,
				);
				
				
				if(empty($id)){
						pdo_insert('micro_test', $data);//添加数据
						message('数据添加成功！', $this->createWebUrl('test', array('op' => 'display')), 'success');
				}else{
						pdo_update('micro_test', $data, array('id' => $id));
						message('数据更新成功！', $this->createWebUrl('test', array('op' => 'display')), 'success');
				}
				
			}else{
				include $this->template('test');
			}
			
		}else if('del' == $op){//删除
		
			if(isset($_GPC['delete'])){
				$ids = implode(",",$_GPC['delete']);
				$sqls = "delete from  ".tablename('micro_test')."  where id in(".$ids.")"; 
				pdo_query($sqls);
				message('删除成功！', referer(), 'success');
			}
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename('micro_test')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				//dump($_GPC);
				message('抱歉，数据不存在或是已经被删除！', $this->createWebUrl('test', array('op' => 'display')), 'error');
			}
			pdo_delete('micro_test', array('id' => $id));
			message('删除成功！', referer(), 'success');
			
		}else if('display' == $op){//显示
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			$condition = '';
			if (!empty($_GPC['keyword'])) {
				$condition .= " and  question LIKE '%".$_GPC['keyword']."%'  ";
			}
			
			$list = pdo_fetchall("SELECT *  FROM ".tablename('micro_test') ." $condition  ORDER BY id DESC LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('micro_test')." $condition" );
			$pager = pagination($total, $pindex, $psize);
			include $this->template('test');
		}
	}
    
    public function doMobileOrderpage() { 
    	$users = pdo_fetchall("SELECT * FROM ".tablename('micro_test_user')." ORDER BY score DESC");
    	$sets = pdo_fetchall("SELECT * FROM ".tablename('micro_testsetting'));
    	include $this->template('user_list');
    } 

	public function doWebParam() {
		global $_W,$_GPC;
		$weid = $_W['weid'];
		load()->func('tpl');
		
		$info = pdo_fetch("SELECT * FROM ".tablename('micro_testsetting'));
 			
		if(checksubmit('submit')){ 
			$title = $_GPC['title'];
				$copyright = $_GPC['copyright'];
				$share_content = $_GPC['share_content'];
				$share_title = $_GPC['share_title'];
				$share_icon = $_GPC['share_icon'];
				$infos = array(
					'title' => $title, 
					'copyright' => $copyright,
					'share_content' => $share_content, 
					'share_title' => $share_title, 
					'share_icon' => $share_icon
				);
			if(empty($info)){
					pdo_insert('micro_testsetting', $infos);//添加数据
					message('数据添加成功！', $this->createWebUrl('param'), 'success');
			}else{
					$id = $info['id'];
					pdo_update('micro_testsetting', $infos, array('id' => $id));
					message('数据更新成功！', $this->createWebUrl('param'), 'success');
			}	
		}
			
		include $this->template('param');
	}
	public function doWebUserinfo() {
		global $_W,$_GPC;
		$weid = $_W['weid'];
		load()->func('tpl');
		$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
		$uinfo = pdo_fetchall("SELECT * FROM ".tablename('micro_test_user'));
		if('del' == $op){
 		if(isset($_GPC['delete'])){
				$ids = implode(",",$_GPC['delete']);
				$sqls = "delete from  ".tablename('micro_test_user')."  where id in(".$ids.")"; 
				pdo_query($sqls);
				message('删除成功！', referer(), 'success');
			}
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename('micro_test_user')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				//dump($_GPC);
				message('抱歉，数据不存在或是已经被删除！', $this->createWebUrl('userinfo'), 'error');
			}
			pdo_delete('micro_test_user', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}	
		include $this->template('userinfo');
	}
	private function  getUserInfo ($access_token, $openid) 
	{
		load()->func('communication');

        $api_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";

        $content = ihttp_get($api_url);

        $userInfo = @json_decode($content['content'], true);

        return $userInfo;

	}
	
}